// set key and secret
var key = 'yourkey'
var secret = 'yoursecret'
var sandbox = true
var callbackUrl = 'https://localhost:3000'

var express = require('express')
var fs = require('fs')
// request body 格式化
var bodyParser = require('body-parser')
var app = express(bodyParser.json())
app.use(bodyParser())
// request body 格式化

var https = require('https')
var http = require('http')
function safetyReadFile(fileName) {
  try {
    return fs.readFileSync(fileName)
  } catch(e) {
    console.log(e);
    process.exit(1);
  }
}

http.createServer(app).listen(3000, function () {
  console.log('Https server listening on port ' + 3000);
});

// 读文件
var id2token = fs.readFileSync('./token.json')
var id2token = JSON.parse(id2token)
var eleme = require('eleme-openapi-sdk');
var Config = eleme.Config;
var OAuthClient = eleme.OAuthClient;
var RpcClient = eleme.RpcClient;

var options = {
  key: key,
  secret: secret,
  sandbox: sandbox, //是否沙箱环境
}

var config = new Config(options);
var oauth_client = new OAuthClient(config)

var rpc_client = null
var shopService = null

// 模版引擎
var mustache = require('mustache');

app.get('/', function(req, res) {
  var code = req.query.code
  // 如果不带code则返回页面
  if (!code) {
    var html = fs.readFileSync('./index.html')
    res.write(html)
    res.end()
  } else {
    oauth_client.getTokenByCode(code, callbackUrl)
      .then(result => {
        var tokenResult = result
        var token = result.access_token
        var rpc_client = new RpcClient(token, config)
        var UserService = eleme.UserService
        var userService = new UserService(rpc_client)
        userService.getUser().then(result => {
          var userId = result.userId
          var shopName = result.authorizedShops[0].name
          id2token[userId] = JSON.stringify(tokenResult)
          fs.writeFileSync('./token.json', JSON.stringify(id2token))

          fs.readFile('./index.html', function(err, template) {
            res.write(mustache.to_html(template.toString(), {
              userId: userId,
              shopName: shopName
            }))
            res.end()
          })

        }).catch(e => {
          console.log(e)
        })
      })
      .catch(e => {
        console.log(e)
      })
    }
});


app.post('/getInfo', function(req, res) {
  var userId = req.body.userId
  var shopId = req.body.shopId
  var response  = {
    result: {},
    error: null
  }
  var tokenInfo = id2token[userId]
  if (tokenInfo) {
    tokenInfo = JSON.parse(id2token[userId])
  } else {
    response.result.OAuthUrl = oauth_client.getOAuthUrl(callbackUrl, 'state')
    res.send(JSON.stringify(response))
    res.end()
    return
  }
  var token = tokenInfo.access_token
  var rpc_client = new RpcClient(token, config)
  var shopService = new eleme.ShopService(rpc_client)
  shopService.getShop(shopId).then(shopDetail => {
    response.result.shopName = shopDetail.name
    res.send(JSON.stringify(response))
    res.end()
  })
  .catch(e => {
    debugger
    console.log('error', e)
    try {
      response.result.OAuthUrl = oauth_client.getOAuthUrl(callbackUrl, 'state')
      res.send(JSON.stringify(response))
      res.end()
    } catch(e) {
      console.log('error', e)
    }
  })
})
